package com.fusingdata.UtilsQR;

/**
 * Created by zj on 2017/10/15.
 * http://www.cnblogs.com/freeliver54/archive/2012/07/30/2615149.html
 */

public class HexUtils {
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * Convert hex string to byte[]
     *
     * @param hexString the hex string
     * @return byte[]
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    /**
     * Convert char to byte
     *
     * @param c char
     * @return byte
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

//    /**
//     * 不够位数的在前面补0，保留num的长度位数字
//     *
//     * @param code
//     * @return
//     */
//    public static String autoGenericCode(String code, int num) {
//        String result = "";
////        // 保留num的位数
////    　　// 0 代表前面补充0
////        // num 代表长度为4
////        // d 代表参数为正数型
//        result = String.format("%0" + num + "d", Integer.parseInt(code));
//        return result;
//    }
}
